/*
 * SocketUDP.cpp
 *
 *  Created on: Jan 24, 2013
 *      Author: murilo
 */

#include "../include/SocketUDP.h"
#include "../include/Exceptions/SocketExceptions.hpp"
#include <cstdlib>
#include <cstring>
#include <iostream>
#define TAM_MAX_MSG 512

Socket_UDP::Socket_UDP(std::string host,std::string port) {
	this->host = host;
	this->port = port;
	memset(&sockType,0,sizeof(sockType));
	sockType.ai_family = AF_UNSPEC;
	sockType.ai_socktype = SOCK_DGRAM;
	connected = false;
}

Socket_UDP::~Socket_UDP() {
	close(socketInfo);
}

void Socket_UDP::connectTo() {
	if(getaddrinfo(host.c_str(),port.c_str(),&sockType,&serverInfo) != 0){
		throw AddressException(host);
	}

	addrinfo *iter = serverInfo;
	for(;iter != NULL;iter = iter->ai_next){
		socketInfo = socket(iter->ai_family,iter->ai_socktype,iter->ai_protocol);
		if(socketInfo == -1){
			throw SocketException();
		}
		if(connect(socketInfo,iter->ai_addr,iter->ai_addrlen) == -1){
			close(socketInfo);
			continue;
		}
		break;
	}
	if(iter == NULL){
		throw ConnectionException();
	}
	freeaddrinfo(serverInfo);
	connected = true;
}

void Socket_UDP::sendMsg(std::string msg) {
	if(send(socketInfo,msg.c_str(),msg.size(),0) == -1){
		throw SendException(msg);
	}
}

std::string Socket_UDP::recvMsg() {
	char* msg;
	std::string msgReceived;

	int recvInfo;
	msg = new char[TAM_MAX_MSG];
	if((recvInfo = recv(socketInfo,msg,TAM_MAX_MSG,0)) == -1){
		if(recvInfo == 0){
			connected = false;
		}
		throw ReceiveMessageException();
	}
	msgReceived.append(std::string(msg));
	return msgReceived;
}

bool Socket_UDP::isConnected() {
	return connected;
}


